define(function(){
	var websocket = null;
	var host=location.host;
	var target="ws://"+host+"/process"
	var ViewModel=function(){
		var self=this;
		var total_count=10000;
		self.progress=ko.observable('0%');
		self.uploads=ko.observableArray([]);
		self.sendMessage=function(){
			send();
		};
		self.closeConn=function(){
			closeWebSocket();
		};
		self.toFixed2=function(a,b){
			return (a*100/b).toFixed(2)+'%';;
		};
		self.data_process=function(data){
			if(data){
				$.each(data,function(index,val){
					var ratio='0%';
					if(val.orderSendCount==val.orderCount){ratio='100%';}else{
						ratio=self.toFixed2(val.orderSendCount,val.orderCount);
					}
					val.ratio=ratio ;
				});
			}
		}
		self.get_uploads=function(){
			$.ajax({
				url:'/order/uploads',
				method:'GET',
				contentType : 'application/json', 
				dataType : 'json',
				cache : false,
				success : function(data) {
					self.data_process(data)
					var mapped_data=ko.mapping.fromJS(data);
					 self.uploads(mapped_data());
				}
			})
		};
		self.refresh=function(upload_id,count){ 
			$.each(self.uploads(),function(index,val){
				if(val.uploadId()==upload_id){
					var ratio=self.toFixed2(count,val.orderCount());
					val.ratio(ratio);
				}
			});
		};
		self.get_uploads();
		self.ws=null;
		self.connect=function(){
			self.ws = new SockJS("/process");
			self.ws.onopen = function () { 
				console.log('Info: WebSocket connection opened.');
			};
			self.ws.onmessage = function (event) {
				var ratio=0;
				var data=JSON.parse(event.data);
				if(data.messageType=="refresh"){
					console.log('refresh data');
					self.get_uploads();
				}else if(data.messageType=="send"){
					console.log(data);
					var message=JSON.parse(data.message);
					var count=parseInt( message.index);
					var upload_id=parseInt( message.upload_id);
					self.refresh(upload_id,count);
				}
				
			};
			self.ws.onclose = function () { 
				console.log('Info: WebSocket connection closed.');
			};
		};
		
		self.connect();
		
	};
	
	var model=new ViewModel();
	ko.applyBindings(model);
});